package so.sao.code.service.domain.entity;

import lombok.Data;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import so.sao.code.service.domain.event.EnterpriseUrlEvent;
import so.sao.code.service.domain.event.query.GetEnterpriseSubDomainEvent;
import so.sao.code.service.domain.event.query.GetEnterpriseUrlsEvent;
import so.sao.code.service.infrastructure.enums.OPERATION;
import so.sao.code.service.infrastructure.enums.SEQ_TYPE;
import so.sao.code.service.infrastructure.enums.convert.SeqTypeConvert;
import so.sao.code.service.infrastructure.jpa.convert.TagBatchTypeConvert;

import javax.persistence.*;
import java.util.List;

import static so.sao.code.service.infrastructure.EventsPublisher.publish;

/**
 * Created by Administrator on 2017/10/19.
 */
@Entity
@Data
@EntityListeners(AuditingEntityListener.class)
public class EnterpriseInfo extends BaseEntity {
    private Long eseId;
    private boolean limit = false;
    //限制子企业往下发码的数量
    private Long limitCount = 0L;
    @Convert(converter = SeqTypeConvert.class)
    private SEQ_TYPE seqType = SEQ_TYPE.BIG;
    private Boolean advEncrypt = false;
    //可用码量
    private Long upCount = 0L;

    private Long createdCount = 0L;
    @Transient
    private List<EnterpriseInfo> childs;
    @Transient
    private String subDomain = "";

    @Version
    private Integer version;
    //    @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST})
//    @JoinColumn(name = "eseId")
    @Transient
    private List<String> urls;

    public List<String> getUrls() {
        if (urls != null) return urls;
        GetEnterpriseUrlsEvent enterpriseUrlsEvent = new GetEnterpriseUrlsEvent(eseId);
        publish(enterpriseUrlsEvent);
        urls = (List<String>) enterpriseUrlsEvent.getResult();
        return urls;
    }

    public String getSubDomain() {
        if (subDomain != null && subDomain != "") return subDomain;
        GetEnterpriseSubDomainEvent event = new GetEnterpriseSubDomainEvent(eseId);
        publish(event);
        subDomain = event.getSubDomain();
        return subDomain;
    }


    public List<EnterpriseInfo> getChilds() {
        return null;
    }

    public void addUrl(String url) {
        publish(new EnterpriseUrlEvent(url, eseId, OPERATION.ADDURL));
    }

    public void delUrl(String url) {
        publish(new EnterpriseUrlEvent(url, eseId, OPERATION.DELURL));
    }
}
